package server;
import java.net.*;
import java.io.*;


/**
 * @author Will Wang;
 * 	student ID: 301171415; 
 * 	contact: dinganw@sfu.ca
 * @this is the assignment 2 of CMPT 431 - distributed system, 2012 Summer
 * 	assignment description: http://www2.cs.sfu.ca/~fedorova/Teaching/CMPT431/Summer2012/assignment2.html
 *  Thanks for TA and instructor for help.
 */


class TCPServer
{
   /**
 * @param argv
 * @throws Exception
 */
	private static String serverIP = "127.0.0.1";
	private static int serverPort = 7896;
	private static String filePath="";
    private static boolean bExit = false;
	
	public static void main(String[] argv) throws Exception
	      {
			parseCommand(argv);
			ServerSocket welcomeSocket=null;	
        	InetAddress add=InetAddress.getByName(serverIP);	
        	Socket clientSocket = null;       
        	while(!bExit)
	         { 
	        	welcomeSocket = new ServerSocket(serverPort,0,add);
	        	 try {
	    			clientSocket= welcomeSocket.accept();
	            } catch (IOException e) {
	                System.err.println("Accept failed.");
	                System.exit(1);
	            }   
	        	//use different thread to process client socket;
	    		serverThread serverTh = new serverThread(clientSocket);	
	    		//if the server is restart, read the log
	    		serverTh.readLastTXNNum();
	    		serverTh.readtxntableTorestart();	
	    		serverThread.setFilePath(filePath);
	    		Thread thread=new Thread(serverTh);
	    		thread.start();
	    		thread.join();
	    		welcomeSocket.close(); 
	         }
        	System.out.println("Gracefully exit!!!");
        	System.exit(0);
	      }//end main

	//parse the command, set the ip, port and file directory
	private static  void parseCommand(String[] command){		
			for(int x=0;x<command.length;++x){
			if(command[x].equals("-h")||command[x].equals("--help")||command[x].equals("-?")){//help option
				printHelpMessage();
				System.exit(0);
			}else if(command[x].equals("-ip")||command[x].equals("-IP")){//ip option 
				serverIP=command[++x];			
			}else if(command[x].equals("-port")||command[x].equals("-Port")||command[x].equals("-PORT")){//port option
				try{
					serverPort=(new Integer(command[++x])).intValue();
				}
				catch(NumberFormatException nfe)
				{
					System.out.println("Invalid port: " + command[x]);
					System.exit(0);
				}
				if(serverPort < 0 || serverPort > 65536)
				{
					System.out.println("Invalid port: " + command[x]);
					System.exit(0);
				}				
			}else if(command[x].equals("-dir")||command[x].equals("-Dir")||command[x].equals("-DIR")){//directory option		
				filePath=command[++x];	
			}else{
				System.out.println("The command format is error, please try again");
				System.exit(-1);
			}//end if-else
		}//end for 
			//to check if the filePath is not blank
			if (filePath.length()==0){
				System.out.println("The command should indicate file path, please try again");
				System.exit(-1);
			}
			System.out.println("Hello. Will listen on " + serverIP + ":" + serverPort);
			System.out.println("The server's filePath: "+filePath);	
	}//end parseCommand

	//print help message about this server
	private static  void printHelpMessage(){
		System.out.println("Please input the command conforming the following format");
		System.out.println("Java TCPServer -ip [ip_address_string] -port [port_number] -dir <directory_path>");
		System.out.println("For example: Java TCPServer -ip 127.0.0.1 -port 8080 -dir /home/docs");
		System.out.println("The -dir argument is required");
		System.out.println("Default ip: 127.0.0.1");
		System.out.println("Default port: 8080 ");
	}	
	
}



